/**
 * 基础的工具方法
 * @type {request}
 */
var request = require('request');
var Promise = require('bluebird');
var crypto = require('crypto');


/**
 * md5加密字符串
 * @param str
 * @returns {*}
 */
exports.md5 = function (str) {
  var md5sum = crypto.createHash('md5');
  md5sum.update(str);
  str = md5sum.digest('hex');
  return str;
};

/**
 * 获取随机字符串
 * @param length
 * @returns {string}
 */
exports.randomString = function(length) { 
  var str = ''
    , maxLength = parseInt(length) || 6
    , chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  while ( str.length !== maxLength ) {
    var random = Math.floor( Math.random() * chars.length ); 
    str += chars[random];
  }
  return str;
}

/**
 * 有效objectId检测
 * @param id
 * @returns {boolean|*}
 */
exports.isValidObjectId = function(id){
    return ObjectId.isValid(id) && /^[0-9a-fA-F]{24}$/.test(id);
}


/**
 * 格式化返回数据 code : -1 失败, 0 成功
 * @param code
 * @param msg
 * @param data
 * @returns {{code: *, msg: *, data: (*|{})}}
 */
exports.parseJSON = function (code, msg, data) {
  return {
    code : code.toString(),
    msg : msg,
    data : data || {}
  }
}